/**
 * 广告页，3秒自动跳转到首页
 */

import 'dart:async';
import 'dart:convert';

import 'package:app/pages/splash_screen_module/splash_model.dart';
import 'package:app/services/address.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../services/dio_manager.dart';
import '../../utils/db_tool.dart';
import '../login_modules/login_view.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  Timer? _timer;

  startTime() async {
    //设置启动图生效时间
    var _duration = new Duration(seconds: 1);
    _timer = new Timer(_duration, navigationPage);
    return _timer;
  }

  void navigationPage() {
    _timer!.cancel();
    Get.to(LoginView());
    // Navigator.of(context).pushReplacementNamed('/main');
  }

  var listData = [];
  var _storageListData = [];          // 存储本地数据
  List cacheSelectList = [];          // 存储需要缓存的数据
  var networkStatus = -1;			  // -1：没有网络 1：wifi  2：4G
  StepTasksDb _stepTaskDb = StepTasksDb();

  /// 打开数据库
   _initDatabase() async {

    String path = await _stepTaskDb.initDatabase();
    // await File(path).delete();       // 删除表
    await _stepTaskDb.open(path);       // 打开表

    _getStorageData();

  }

  /// 获取本地数据
   _getStorageData() async {
    var data = await _stepTaskDb.getData(type: 'openAD');

    print('data = = = = = = = = = ${data}');
    setState(() {
      _storageListData = data;           // 先赋值一次 以便添加时使用
    });
  }

  /// insert data
   insertData(var json)async{
     // 创建要存储本地的数据
     var dataBase = {
       'step_listData': jsonEncode(json),
     };

     // 不为空的话，证明拿到了正常数据，将其存储到要存储的数据参数中
       dataBase['assets_listDetails'] = jsonEncode(json);

     // 进行本地缓存
     var db_res = await _stepTaskDb.
     insert(StepTasks(stepListType:'openAD', stepListData:dataBase['step_listData'], stepDataDetails:dataBase['assets_listDetails']));

     print('db_res === ${db_res}');

  }

  ///
   requestDataWithAppOpens() async {

     _initDatabase();


     var json = await DioManager().kkRequest(Address.appOpens,method: 'get');

    SplashModel model = SplashModel.fromJson(json);

    insertData(json);

    if(_storageListData.isNotEmpty){
      var jsonStr = _storageListData[0]['step_listData'];
      var json = jsonDecode(jsonStr);
      SplashModel model = SplashModel.fromJson(json);
      print('eeeeeeeeeeeeee = ${model.data?.details?[0].url}');
    }

    setState(() {

    });

  }

  @override
  void initState() {
    super.initState();

    requestDataWithAppOpens();

    startTime();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: Image.asset(
          "images/y8.png",
          fit: BoxFit.fill,
        ),
      ),
    );
  }
}
